#include "mytranslator.h"
#include <QDir>
#include "myapp.h"


MyTranslator::MyTranslator(QObject* parent)
		: QObject(parent)
{
}


void MyTranslator::retranslate(const QString &lang)
{
	if ( !currentTranslationLang.isNull() ) {
		foreach(QTranslator *tr, currentTranslations) {
			qApp->removeTranslator(tr);
			tr->deleteLater();
		}
		currentTranslations.clear();
		currentTranslationLang = QString::null;
	}
	/*if ( !files_langs.contains(lang) and lang == "English" ) return; // English is built in
	else if ( !files_langs.contains(lang) ) return; // probably English. Or mistake*/
	foreach(const QString langFile, files_langs[lang]) {
		QTranslator *tr = new QTranslator();
		if ( tr->load(langFile) ) {
			qApp->installTranslator(tr);
			currentTranslations.append(tr);
		} else {
			files_langs[lang].removeAll(langFile); // seams file broken
		}
	}
	qDebug() << trUtf8("Retranslated to") << trUtf8("English");
	currentTranslationLang = lang;
	emit retranslateUi();
}




void MyTranslator::loadFiles()
{
	files_langs.clear();
	langIndexes.clear();
	foreach(QString dir, MyApp::resourcesDirs())
	{
		QDir resDir(dir);
		QStringList translateFiles = resDir.entryList(QStringList() << "*.qm");
		foreach(QString file, translateFiles)
		{
			QTranslator tempTr;
			if ( tempTr.load(file, dir) ) {
				QString lang = tempTr.translate("MyTranslator", "English");
				if ( !lang.isEmpty() ) {
					files_langs[lang] += dir + "/" + file;
					addLang(lang);
				}
			}
		}
	}
	qDebug() << trUtf8("Languages:") << files_langs;
//	retranslate(QString::fromUtf8("Русский"));
}

void MyTranslator::addLang(const QString &langName)
{
	if ( ! this->langIndexes.contains( langName ) )
		this->langIndexes.append( langName );
}

